Passed
Pull Request — filestream (#169)
by
unknown
01:41
created

util-file.ts ➔ getNextBufferSubarrayAsync   A

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 10
rs 9.95
c 0
b 0
f 0
cc 1
1
import * as fs from 'fs'
2
import { promisify } from 'util'
3
4
export const fsOpenPromise = promisify(fs.open)
5
export const fsReadPromise = promisify(fs.read)
6
export const fsClosePromise = promisify(fs.close)
7
export const fsWritePromise = promisify(fs.write)
8
export const fsUnlinkPromise = promisify(fs.unlink)
9
export const fsRenamePromise = promisify(fs.rename)
10
export const fsExistsPromise = promisify(fs.exists)
11
export const fsWriteFilePromise = promisify(fs.writeFile)
12
13
/**
14
 * @returns true if the file existed
15
 */
16
export function unlinkIfExistSync(filepath: string) {
17
    const exist = fs.existsSync(filepath)
18
    if (exist) {
19
        fs.unlinkSync(filepath)
20
    }
21
    return exist
22
}
23
24
/**
25
 * @returns true if the file existed
26
 */
27
export async function unlinkIfExist(filepath: string) {
28
    const exist = await fsExistsPromise(filepath)
29
    if (exist) {
30
        await fsUnlinkPromise(filepath)
31
    }
32
    return exist
33
}
34
35
export function processFileSync<T>(
36
    filepath: string,
37
    flags: string,
38
    process: (fileDescriptor: number) => T
39
) {
40
    const fileDescriptor = fs.openSync(filepath, flags)
41
    try {
42
        return process(fileDescriptor)
43
    }
44
    finally {
45
        fs.closeSync(fileDescriptor)
46
    }
47
}
48
49
export async function processFileAsync<T>(
50
    filepath: string,
51
    flags: string,
52
    process: (fileDescriptor: number) => Promise<T>
53
): Promise<T> {
54
    const fileDescriptor = await fsOpenPromise(filepath, flags)
55
    try {
56
        return await process(fileDescriptor)
57
    }
58
    finally {
59
        await fsClosePromise(fileDescriptor)
60
    }
61
}
62
63
export function fillBufferSync(
64
    fileDescriptor: number,
65
    buffer: Buffer,
66
    offset = 0
67
): Buffer {
68
    const bytesRead = fs.readSync(
69
        fileDescriptor,
70
        buffer,
71
        offset,
72
        buffer.length - offset,
73
        null
74
    )
75
    return buffer.subarray(0, bytesRead + offset)
76
}
77
78
export async function fillBufferAsync(
79
    fileDescriptor: number,
80
    buffer: Buffer,
81
    offset = 0
82
): Promise<Buffer> {
83
    const bytesRead = (await fsReadPromise(
84
        fileDescriptor,
85
        buffer,
86
        offset,
87
        buffer.length - offset,
88
        null
89
    )).bytesRead
90
    return buffer.subarray(0, bytesRead + offset)
91
}
92